import re
import requests
from urllib.parse import urljoin


# 思路：在网络中找到两个m3u8文件的请求网址为
# https://vod6.bdzybf7.com/20231118/cUYHi2tB/index.m3u8
# https://vod6.bdzybf7.com/20231118/cUYHi2tB/1500kb/hls/index.m3u8

# 第一个m3u8响应：
# #EXTM3U
# #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1500000,RESOLUTION=1280x720
# /20231118/cUYHi2tB/1500kb/hls/index.m3u8
# 第二个m3u8响应了很多ts文件
# 根据第一个m3u8和其响应的内容拼凑出第二个m3u8的url
# 用第二个m3u8下载所有ts文件
# 合并所有视频

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

# Session对象可以在多个请求之间保持某些参数，如cookies、认证信息等，使得这些请求看起来像是同一个用户会话中的操作。
# requests.adapters.DEFAULT_RETRIES = 5
session = requests.session()
requests.packages.urllib3.disable_warnings()  # 关闭安全警告
session.get('https://www.yayameiju.com/', headers=headers,verify=False)  # 忽略https安全证书的验证
# 请求当前电影网址（地狱厨房）
url = 'https://www.yayameiju.com/play/53231-0-0.html'
resp = session.get(url, headers=headers)
resp.encoding = 'UTF-8'
data = resp.text
# 写到文件中方便对内容进行分析
with open('../协程/电影.html', 'w', encoding='UTF-8') as f:
    f.write(data)
with open('../协程/电影.html', 'r', encoding='UTF-8') as f:
    data = f.read()
# var now="https://vod6.bdzybf7.com/20231118/cUYHi2tB/index.m3u8";var pn="dbm3u8"; var next="https://vod6.bdzybf7.com/20231118/iPLekGYl/index.m3u8";
# 正则匹配第一个m3u8地址，
rege = r'now="(.*?index\.m3u8)"'
match = re.search(rege, data)
first_m3u8_url = match.group(1)
print(first_m3u8_url)
# https://vod6.bdzybf7.com/20231118/cUYHi2tB/index.m3u8
# 请求第一个m3u8url
resp=session.get(first_m3u8_url,headers=headers)
with open('first_m3u8_url.text','wb')as f:
    f.write(resp.content)
resp.encoding='UTF-8'


# 根据第一个m3u8和其响应的内容拼凑出第二个m3u8的url

# https://vod6.bdzybf7.com/20231118/cUYHi2tB/index.m3u8
# https://vod6.bdzybf7.com/20231118/cUYHi2tB/1500kb/hls/index.m3u8

'''#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1500000,RESOLUTION=1280x720
/20231118/cUYHi2tB/1500kb/hls/index.m3u8
'''

with open('first_m3u8_url.text','r')as f:
    data=f.read()
print(data.split('/',3)[-1].strip())  #根据第三个/进行分割 ，去掉末尾的/n！！！
print(urljoin(first_m3u8_url,data.split('/',3)[-1].strip()))
# https://vod6.bdzybf7.com/20231118/cUYHi2tB/1500kb/hls/index.m3u8
# 再次请求第二个m3u8的url
second_m3u8_url=urljoin(first_m3u8_url,data.split('/',3)[-1].strip())
resp=session.get(second_m3u8_url,headers=headers)
with open('second_m3u8_url.text','wb')as f:
    f.write(resp.content)
resp.encoding='UTF-8'
# ok!!!
